<?php
namespace app\middleware;

use Closure;
use think\Response;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class CheckToken
{
    public function handle($request, Closure $next)
    {
        // 从请求中获取 token（通常在请求头中）
        $token = $request->header('Authorization');

        // 验证 token（假设你有一个验证 token 的方法）
        if (!empty($token) && !$this->validateToken($request,$token)) {
            return Response::create(['error' => 'Invalid token'], 'json', 401);
        }
        $response = $next($request);
        return $response;
    }

    protected function validateToken($request,$token)
    {
        try {

            $token = str_replace('Bearer ', '', $token);
            $key = '!@#$%*&';
            JWT::$leeway = 60; //当前时间减去60，把时间留点余地
            $decoded = JWT::decode($token, new Key($key, 'HS256'));
            $userdata = $decoded->data;
            $request->user = $userdata;
        }catch (\Firebase\JWT\ExpiredException $e) {
            return false; // Token过期
        }

        return true;
    }

}
